package com.interagriculture.controller;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.interagriculture.annotation.AdminVerify;
import com.interagriculture.common.Constants;
import com.interagriculture.common.CustomException;
import com.interagriculture.common.Result;
import com.interagriculture.entity.dto.LoginDto;
import com.interagriculture.entity.vo.CheckCodeVO;
import com.interagriculture.enums.ExceptionCodeEnum;
import com.interagriculture.service.AdminService;
import com.interagriculture.utils.CacheContainerUtil;
import com.interagriculture.utils.MD5Util;
import com.interagriculture.utils.StringTools;
import com.interagriculture.utils.ThreadLocalUtil;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @author 10 2024/10/24
 */
@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AdminService adminService;
    private static Logger logger = Logger.getLogger(LoginController.class.toString());

    @CrossOrigin
    @PostMapping("/verifyCode")
    public Result verifyCode(){
        logger.info("info输出日志");
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(100, 42);
        //获取小写验证码
        String code = arithmeticCaptcha.text().toLowerCase();
        log.info("code:{}",code);
        String checkCodeKey = Constants.验证码Key + MD5Util.encrypt(UUID.randomUUID().toString());
        //验证码转成base64格式
        String checkCodeBase64 = arithmeticCaptcha.toBase64();
        CheckCodeVO checkCodeVO = new CheckCodeVO(checkCodeBase64, checkCodeKey);
        //放入guava缓存 用于验证验证码
        CacheContainerUtil.putCheckCode(checkCodeKey,code);
        return Result.ok(checkCodeVO);
    }


    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto){

        String session = adminService.loginCheck(loginDto);
        HashMap<String, String> map = new HashMap<>();
        map.put("session",session);
        return Result.ok(map);
    }

    @PostMapping("/logout")
    @AdminVerify
    public Result logout(){
        CacheContainerUtil.removeSession(ThreadLocalUtil.get().getSession());
        ThreadLocalUtil.remove();
        return Result.ok();
    }
}
